<template>
    <div id="container" class="super_amap flex-column"></div>
</template>
<script>
import { getCache } from '@/utils/session';
import { getStatistics, getMapStatistics } from '@/api/supervision/map';
import { mapState } from 'vuex';

export default {
    name: 'ShowMapMarker',
    dicts: ['city'],
    data() {
        let self = this;
        let userInfo = getCache('userInfo') || { userId: '' };
        let { userId } = userInfo;
        return {
            userId,
            roadIcon: require('@/assets/map/scheme.png'),
            loading: true,
            map: null,
            labelMarkerList: [],
            roadList: [],
            markerList: [],
            timer: null
        };
    },
    computed: {
        ...mapState({
            userArea: state => state.user.userArea
        })
    },
    mounted() {
        this.$nextTick(() => {
            this.timer = setTimeout(() => {
                this.initMap();
            }, 200);
        });
    },
    methods: {
        initMap() {
            try{
                var map = new AMap.Map('container', {
                    zoom: 9,
                    showLabel: true,
                    expandZoomRange: true,
                    pitch: 60,
                    mapStyle: 'amap://styles/whitesmoke'
                });
                if(!map.loaded){
                    this.$emit('mapErrorLoad');
                }
                var layer = new AMap.LabelsLayer({
                    // 开启标注避让，默认为开启，v1.4.15 新增属性
                    collision: true,
                    // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
                    animation: true
                });
                map.add(layer);
                this.layer = layer;
                this.map = map;
                this.status = '';
                this.getMapList();
                this.searchCity();
                // map.on('zoomchange', () => {
                //     let zoom = map.getZoom();
                // });
            }catch(err){
                console.log(err)
                location.reload();
            }
        },
        createRoadLabel(data) {
            for (var i = 0; i < data.length; i++) {
                var curData = data[i];
                curData.extData = {
                    index: curData.id
                };
                var labelMarker = new AMap.LabelMarker(curData);
                this.labelMarkerList.push(labelMarker);
                this.layer.add(labelMarker);
                labelMarker.on('click', e => {
                    let { position } = e.data.data;
                    this.map.setZoom(13); //放大地图
                    this.map.setCenter(position);
                });
            }
            this.map.setFitView();
        },
        //搜索城市
        searchCity() {
            //区域重点
            let { area } = this.userArea;
            let areaBox = area ? area.split('/') : [];
            let city = areaBox[areaBox.length - 1];
            if (city == '全国' || !area) return false;
            AMap.plugin('AMap.DistrictSearch', () => {
                var districtSearch = new AMap.DistrictSearch({
                    // 关键字对应的行政区级别，共有5种级别
                    level: 'province',
                    // 是否显示下级行政区级数，1表示返回下一级行政区
                    subdistrict: 0,
                    // 返回行政区边界坐标点
                    extensions: 'all'
                });

                districtSearch.search(city, (status, result) => {
                    // 查询成功时，result即为对应的行政区信息
                    if (status == 'complete') {
                        let { districtList } = result;
                        let bounds = districtList[0].boundaries;
                        if (bounds) {
                            const path = [];
                            for (let i = 0, l = bounds[0].length; i < l; i++) {
                                let item = bounds[0][i];
                                let point = [item.lng, item.lat];
                                path.push(point);
                            }
                            var polygon = new AMap.Polygon({
                                path: path,
                                strokeColor: '#0069CA',
                                strokeWeight: 3,
                                strokeOpacity: 0.7,
                                fillOpacity: 0.3,
                                fillColor: '#0069CA',
                                zIndex: 1
                            });
                            this.map.add(polygon);
                            // 缩放地图到合适的视野级别
                            this.map.setFitView([polygon]);
                        }
                    }
                });
            });
        },
        //获取施工地图
        async getMapList() {
            try {
                let userId = this.userId;
                let city = this.city;
                let status = this.status;
                let res = await getMapStatistics({ userId, status, city });
                let { data } = res;
                let roadList = [];
                let markerList = [];
                data &&
                    data.length &&
                    data.map(item => {
                        let {
                            id,
                            workingSection,
                            startStationId,
                            workingStatus,
                            startStationName,
                            startStationLatitude,
                            startStationLongitude,
                            endStationId,
                            endStationName,
                            endStationLatitude,
                            endStationLongitude
                        } = item;
                        let roadIndex = roadList.findIndex(road => road.name == workingSection);
                        let roadColor = '';
                        switch (workingStatus) {
                            case '施工中':
                                roadColor = '#00BB96';
                                break;
                            case '超时':
                                roadColor = '#F75444';
                                break;
                            case '待整改':
                                roadColor = '#FF9C1D';
                                break;
                            default:
                                roadColor = '#1084D1';
                                break;
                        }
                        if (startStationLatitude) {
                            let startItem = {
                                id: startStationId,
                                name: startStationName,
                                position: [startStationLongitude, startStationLatitude],
                                lng: startStationLongitude,
                                lat: startStationLatitude,
                                opacity: 1,
                                zooms: [7, 20],
                                zIndex: 11,
                                icon: {
                                    type: 'image',
                                    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                                    size: [25, 34],
                                    offset: new AMap.Pixel(-13, -30),
                                    anchor: 'bottom-center',
                                    angel: 0,
                                    retina: true
                                },
                                text: {
                                    content: startStationName,
                                    direction: 'top',
                                    offset: [0, 0],
                                    style: {
                                        fontSize: 13,
                                        fontWeight: 'normal',
                                        fillColor: '#fff',
                                        padding: '2, 5',
                                        backgroundColor: roadColor
                                    }
                                }
                            };
                            let endItem = {
                                id: endStationId,
                                name: endStationName,
                                lng: endStationLongitude,
                                lat: endStationLatitude,
                                position: [endStationLongitude, endStationLatitude],
                                zooms: [7, 20],
                                opacity: 1,
                                zIndex: 11,
                                icon: {
                                    type: 'image',
                                    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                                    size: [25, 34],
                                    offset: new AMap.Pixel(-13, -30),
                                    anchor: 'bottom-center',
                                    angel: 0,
                                    retina: true
                                },
                                text: {
                                    content: endStationName,
                                    direction: 'top',
                                    offset: [0, 0],
                                    style: {
                                        fontSize: 13,
                                        fontWeight: 'normal',
                                        fillColor: '#fff',
                                        padding: '2, 5',
                                        backgroundColor: roadColor
                                    }
                                }
                            };
                            markerList.push(startItem);
                            markerList.push(endItem);
                            //存在路段
                            if (roadIndex != -1) {
                                roadList[roadIndex].children.push(startItem);
                                roadList[roadIndex].children.push(endItem);
                            } else {
                                roadList.push({
                                    id: id,
                                    name: workingSection,
                                    position: [startStationLongitude - 0.01, startStationLatitude - 0.01],
                                    lng: startStationLongitude,
                                    lat: startStationLatitude,
                                    zooms: [3, 13],
                                    children: [startItem, endItem],
                                    opacity: 1,
                                    zIndex: 10,
                                    icon: {
                                        type: 'image',
                                        image: this.roadIcon,
                                        size: [34, 46],
                                        offset: new AMap.Pixel(-17, -40),
                                        anchor: 'bottom-center',
                                        angel: 0,
                                        retina: true
                                    },
                                    text: {
                                        content: workingSection,
                                        direction: 'top',
                                        offset: [0, 0],
                                        style: {
                                            fontSize: 13,
                                            fontWeight: 'normal',
                                            fillColor: '#fff',
                                            padding: '2, 5',
                                            backgroundColor: '#0058BF'
                                        }
                                    }
                                });
                            }
                        }
                    });
                this.roadList = roadList;
                this.markerList = markerList;
                this.createRoadLabel([...markerList, ...roadList]);
            } finally {
            }
        }
    },
    beforeDestroy() {
        this.map.destroy();
        this.map = null;
        clearTimeout(this.timer);
    }
};
</script>

<style lang="scss" scoped>
.supervision_map,
.super_amap {
    position: relative;
    overflow: hidden;
    ::v-deep .ant-spin-container {
        display: flex;
        flex: 1;
        flex-direction: column;
    }

    & > ::v-deep .el-vue-amap {
        display: flex;
        flex: 1;
    }
}
</style>
